package com.bawei.lib_common.utils

import android.view.MotionEvent
import android.view.View
import androidx.recyclerview.widget.RecyclerView

/**
 * 滑动冲突解决工具类
 */
object ScrollConflictUtils {
    
    /**
     * 解决RecyclerView与父容器ScrollView的滑动冲突
     * @param recyclerView 需要处理滑动冲突的RecyclerView
     * @param isHorizontal 是否为水平滚动的RecyclerView
     */
    fun resolveScrollConflict(recyclerView: RecyclerView, isHorizontal: Boolean = false) {
        val touchSlop = 10f // 触摸滑动阈值
        
        recyclerView.addOnItemTouchListener(object : RecyclerView.OnItemTouchListener {
            private var startX = 0f
            private var startY = 0f
            private var isScrolling = false
            
            override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
                when (e.action) {
                    MotionEvent.ACTION_DOWN -> {
                        startX = e.x
                        startY = e.y
                        isScrolling = false
                    }
                    MotionEvent.ACTION_MOVE -> {
                        if (!isScrolling) {
                            val deltaX = Math.abs(e.x - startX)
                            val deltaY = Math.abs(e.y - startY)
                            
                            if (isHorizontal) {
                                // 水平滚动：如果水平滑动距离大于垂直滑动距离且超过阈值，拦截事件
                                if (deltaX > deltaY && deltaX > touchSlop) {
                                    isScrolling = true
                                    return true
                                } else if (deltaY > deltaX && deltaY > touchSlop) {
                                    // 垂直滑动，不拦截
                                    return false
                                }
                            } else {
                                // 垂直滚动：如果垂直滑动距离大于水平滑动距离且超过阈值，拦截事件
                                if (deltaY > deltaX && deltaY > touchSlop) {
                                    isScrolling = true
                                    return true
                                } else if (deltaX > deltaY && deltaX > touchSlop) {
                                    // 水平滑动，不拦截
                                    return false
                                }
                            }
                        }
                    }
                    MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                        isScrolling = false
                    }
                }
                return false
            }
            
            override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {
                // 不需要处理
            }
            
            override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
                // 不需要处理
            }
        })
    }
    
    /**
     * 为容器View设置滑动冲突处理
     * @param containerView 容器View
     * @param childView 子View（通常是RecyclerView）
     * @param isHorizontal 子View是否为水平滚动
     */
    fun setupContainerScrollConflict(containerView: View, childView: View, isHorizontal: Boolean = false) {
        val touchSlop = 10f
        var startX = 0f
        var startY = 0f
        
        containerView.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    // 记录起始触摸点
                    startX = event.x
                    startY = event.y
                }
                MotionEvent.ACTION_MOVE -> {
                    val deltaX = Math.abs(event.x - startX)
                    val deltaY = Math.abs(event.y - startY)
                    
                    if (isHorizontal) {
                        // 如果是水平滑动且滑动距离足够大，阻止父容器拦截
                        if (deltaX > deltaY && deltaX > touchSlop) {
                            childView.parent?.requestDisallowInterceptTouchEvent(true)
                        }
                    } else {
                        // 如果是垂直滑动且滑动距离足够大，阻止父容器拦截
                        if (deltaY > deltaX && deltaY > touchSlop) {
                            childView.parent?.requestDisallowInterceptTouchEvent(true)
                        }
                    }
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    // 恢复父容器的触摸拦截
                    childView.parent?.requestDisallowInterceptTouchEvent(false)
                }
            }
            false
        }
    }
    
    /**
     * 解决嵌套滚动冲突的完整方案
     * @param recyclerView 需要处理滑动冲突的RecyclerView
     * @param containerView 容器View
     * @param isHorizontal 是否为水平滚动
     */
    fun resolveNestedScrollConflict(
        recyclerView: RecyclerView, 
        containerView: View, 
        isHorizontal: Boolean = false
    ) {
        // 为RecyclerView设置触摸事件处理
        resolveScrollConflict(recyclerView, isHorizontal)
        
        // 为容器View设置触摸事件处理
        setupContainerScrollConflict(containerView, recyclerView, isHorizontal)
    }
    
    /**
     * 为ViewPager2设置滑动冲突处理
     * @param viewPager ViewPager2实例
     * @param isHorizontal 是否为水平滑动
     */
    fun resolveViewPagerScrollConflict(viewPager: androidx.viewpager2.widget.ViewPager2, isHorizontal: Boolean = true) {
        val touchSlop = 10f
        var startX = 0f
        var startY = 0f
        
        viewPager.setOnTouchListener { _, event ->
            when (event.action) {
                MotionEvent.ACTION_DOWN -> {
                    startX = event.x
                    startY = event.y
                }
                MotionEvent.ACTION_MOVE -> {
                    val deltaX = Math.abs(event.x - startX)
                    val deltaY = Math.abs(event.y - startY)
                    
                    if (isHorizontal) {
                        // 水平滑动时，如果水平距离大于垂直距离，阻止父容器拦截
                        if (deltaX > deltaY && deltaX > touchSlop) {
                            viewPager.parent?.requestDisallowInterceptTouchEvent(true)
                        }
                    } else {
                        // 垂直滑动时，如果垂直距离大于水平距离，阻止父容器拦截
                        if (deltaY > deltaX && deltaY > touchSlop) {
                            viewPager.parent?.requestDisallowInterceptTouchEvent(true)
                        }
                    }
                }
                MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                    viewPager.parent?.requestDisallowInterceptTouchEvent(false)
                }
            }
            false
        }
    }
    
    /**
     * 专门解决ViewPager2与内部水平滚动RecyclerView的冲突
     * 这个方法会阻止ViewPager2在RecyclerView区域响应水平滑动
     * @param viewPager ViewPager2实例
     * @param recyclerView 水平滚动的RecyclerView
     */
    fun resolveViewPagerWithHorizontalRecyclerView(
        viewPager: androidx.viewpager2.widget.ViewPager2,
        recyclerView: RecyclerView
    ) {
        val touchSlop = 10f
        var startX = 0f
        var startY = 0f
        var isInRecyclerView = false
        
        // 为RecyclerView设置触摸事件处理
        recyclerView.addOnItemTouchListener(object : RecyclerView.OnItemTouchListener {
            override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
                when (e.action) {
                    MotionEvent.ACTION_DOWN -> {
                        startX = e.x
                        startY = e.y
                        isInRecyclerView = true
                    }
                    MotionEvent.ACTION_MOVE -> {
                        val deltaX = Math.abs(e.x - startX)
                        val deltaY = Math.abs(e.y - startY)
                        
                        // 如果是水平滑动且滑动距离足够大，拦截事件并阻止ViewPager2响应
                        if (deltaX > deltaY && deltaX > touchSlop) {
                            // 阻止ViewPager2的父容器拦截触摸事件
                            viewPager.parent?.requestDisallowInterceptTouchEvent(true)
                            return true
                        }
                    }
                    MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                        isInRecyclerView = false
                        // 恢复ViewPager2的触摸拦截
                        viewPager.parent?.requestDisallowInterceptTouchEvent(false)
                    }
                }
                return false
            }
            
            override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {
                // 不需要处理
            }
            
            override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
                // 不需要处理
            }
        })
        
        // 为RecyclerView的父容器也设置触摸事件处理
        recyclerView.parent?.let { parent ->
            if (parent is View) {
                parent.setOnTouchListener { _, event ->
                    when (event.action) {
                        MotionEvent.ACTION_DOWN -> {
                            startX = event.x
                            startY = event.y
                        }
                        MotionEvent.ACTION_MOVE -> {
                            val deltaX = Math.abs(event.x - startX)
                            val deltaY = Math.abs(event.y - startY)
                            
                            // 如果是水平滑动且滑动距离足够大，阻止ViewPager2响应
                            if (deltaX > deltaY && deltaX > touchSlop) {
                                viewPager.parent?.requestDisallowInterceptTouchEvent(true)
                            }
                        }
                        MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                            // 恢复ViewPager2的触摸拦截
                            viewPager.parent?.requestDisallowInterceptTouchEvent(false)
                        }
                    }
                    false
                }
            }
        }
    }
    
    /**
     * 为ScrollView内的水平滚动RecyclerView设置滑动冲突处理
     * @param scrollView ScrollView实例
     * @param recyclerView 水平滚动的RecyclerView
     */
    fun resolveScrollViewWithHorizontalRecyclerView(
        scrollView: android.widget.ScrollView,
        recyclerView: RecyclerView
    ) {
        val touchSlop = 10f
        var startX = 0f
        var startY = 0f
        
        // 为RecyclerView设置触摸事件处理
        recyclerView.addOnItemTouchListener(object : RecyclerView.OnItemTouchListener {
            override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
                when (e.action) {
                    MotionEvent.ACTION_DOWN -> {
                        startX = e.x
                        startY = e.y
                    }
                    MotionEvent.ACTION_MOVE -> {
                        val deltaX = Math.abs(e.x - startX)
                        val deltaY = Math.abs(e.y - startY)
                        
                        // 如果是水平滑动且滑动距离足够大，拦截事件并阻止ScrollView响应
                        if (deltaX > deltaY && deltaX > touchSlop) {
                            // 阻止ScrollView拦截触摸事件
                            scrollView.requestDisallowInterceptTouchEvent(true)
                            return true
                        }
                    }
                    MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                        // 恢复ScrollView的触摸拦截
                        scrollView.requestDisallowInterceptTouchEvent(false)
                    }
                }
                return false
            }
            
            override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {
                // 不需要处理
            }
            
            override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
                // 不需要处理
            }
        })
    }
    
    /**
     * 简化版：解决ScrollView内水平滚动RecyclerView的滑动冲突
     * 这个方法会自动查找ScrollView父容器
     * @param recyclerView 水平滚动的RecyclerView
     */
    fun resolveHorizontalRecyclerViewInScrollView(recyclerView: RecyclerView) {
        val touchSlop = 10f
        var startX = 0f
        var startY = 0f
        
        // 查找ScrollView父容器
        var parent = recyclerView.parent
        var scrollView: android.widget.ScrollView? = null
        
        while (parent != null) {
            if (parent is android.widget.ScrollView) {
                scrollView = parent
                break
            }
            parent = parent.parent
        }
        
        if (scrollView == null) {
            // 如果没有找到ScrollView，使用默认的父容器处理
            recyclerView.addOnItemTouchListener(object : RecyclerView.OnItemTouchListener {
                override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
                    when (e.action) {
                        MotionEvent.ACTION_DOWN -> {
                            startX = e.x
                            startY = e.y
                        }
                        MotionEvent.ACTION_MOVE -> {
                            val deltaX = Math.abs(e.x - startX)
                            val deltaY = Math.abs(e.y - startY)
                            
                            if (deltaX > deltaY && deltaX > touchSlop) {
                                recyclerView.parent?.requestDisallowInterceptTouchEvent(true)
                                return true
                            }
                        }
                        MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                            recyclerView.parent?.requestDisallowInterceptTouchEvent(false)
                        }
                    }
                    return false
                }
                
                override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {
                    // 不需要处理
                }
                
                override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
                    // 不需要处理
                }
            })
            return
        }
        
        // 为RecyclerView设置触摸事件处理
        recyclerView.addOnItemTouchListener(object : RecyclerView.OnItemTouchListener {
            override fun onInterceptTouchEvent(rv: RecyclerView, e: MotionEvent): Boolean {
                when (e.action) {
                    MotionEvent.ACTION_DOWN -> {
                        startX = e.x
                        startY = e.y
                    }
                    MotionEvent.ACTION_MOVE -> {
                        val deltaX = Math.abs(e.x - startX)
                        val deltaY = Math.abs(e.y - startY)
                        
                        // 如果是水平滑动且滑动距离足够大，拦截事件并阻止ScrollView响应
                        if (deltaX > deltaY && deltaX > touchSlop) {
                            // 阻止ScrollView拦截触摸事件
                            scrollView.requestDisallowInterceptTouchEvent(true)
                            return true
                        }
                    }
                    MotionEvent.ACTION_UP, MotionEvent.ACTION_CANCEL -> {
                        // 恢复ScrollView的触摸拦截
                        scrollView.requestDisallowInterceptTouchEvent(false)
                    }
                }
                return false
            }
            
            override fun onTouchEvent(rv: RecyclerView, e: MotionEvent) {
                // 不需要处理
            }
            
            override fun onRequestDisallowInterceptTouchEvent(disallowIntercept: Boolean) {
                // 不需要处理
            }
        })
    }
    
    /**
     * 测试滑动冲突解决方案是否有效
     * @param recyclerView 要测试的RecyclerView
     * @return 是否成功设置了滑动冲突处理
     */
    fun testScrollConflictResolution(recyclerView: RecyclerView): Boolean {
        try {
            // 检查RecyclerView是否有LayoutManager
            if (recyclerView.layoutManager == null) {
                return false
            }
            
            // 检查是否为水平滚动
            val isHorizontal = recyclerView.layoutManager?.canScrollHorizontally() == true
            if (!isHorizontal) {
                return false
            }
            
            // 应用滑动冲突解决方案
            resolveHorizontalRecyclerViewInScrollView(recyclerView)
            
            // 简单验证：检查RecyclerView是否仍然可以正常工作
            return recyclerView.layoutManager != null && 
                   recyclerView.layoutManager?.canScrollHorizontally() == true
        } catch (e: Exception) {
            return false
        }
    }
} 